package com.dao;

import java.sql.Timestamp;

import org.hibernate.Query;
import org.hibernate.Session;

import com.base.BaseDao;
import com.bean.RoleInfo;
import com.bean.SysUser;
import com.bean.UserLogin;
import com.util.EncoderHandler;

public class LoginDao extends BaseDao {
	
	/**
	 * 登录
	 * <p>Title: login</p>
	 * <p>Description: </p>
	 * @param user 用户信息，必须包含用户名和密码
	 * @param ip
	 * @return
	 * @throws Exception
	 */
	public SysUser login(SysUser user,String ip) throws Exception{
		
		Session session = this.getSession();
		UserLogin userLogin = new UserLogin();
		Query query = session.createQuery("from SysUser u where u.userName=:username and u.userPasswd=:pwd");
		query.setParameter("username", user.getUserName());
		query.setParameter("pwd", EncoderHandler.MD5(user.getUserPasswd()));
		
		SysUser user2= (SysUser)query.uniqueResult();
		
		if(user2!=null){
			query = session.createQuery("from RoleInfo r where r.roleId= "+user2.getRole());
			RoleInfo roleInfo = (RoleInfo)query.uniqueResult();
//			System.out.println("query="+query.getQueryString());
			userLogin.setLoginId(user2.getSysUserId());
			userLogin.setLoginIp(ip);
			userLogin.setLoginTime(new Timestamp(System.currentTimeMillis()));
			session.save(userLogin);
			if(roleInfo!=null)
				user2.setRoleName(roleInfo.getRoleName());
		}
		return user2;
	}
}
